package org.easydev.base.webbase.util;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class WebUtil {

    public static String getClientIp(HttpServletRequest request) {
        // 1. 检查常见的代理头部（注意头部名称可能因代理配置而异）
        String[] headersToCheck = {
                "X-Forwarded-For",
                "Proxy-Client-IP",
                "WL-Proxy-Client-IP",
                "HTTP_X_FORWARDED_FOR",
                "HTTP_X_FORWARDED",
                "HTTP_X_CLUSTER_CLIENT_IP",
                "HTTP_CLIENT_IP",
                "HTTP_FORWARDED_FOR",
                "HTTP_FORWARDED",
                "HTTP_VIA",
                "REMOTE_ADDR"
        };

        // 2. 遍历所有可能的头部
        for (String header : headersToCheck) {
            String ip = request.getHeader(header);
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                // 3. 处理X-Forwarded-For的特殊情况（可能包含多个IP）
                if ("X-Forwarded-For".equalsIgnoreCase(header)) {
                    ip = ip.split(",")[0]; // 取第一个IP
                }
                return ip.trim();
            }
        }

        // 4. 如果所有头部都无效，回退到直接连接IP
        return request.getRemoteAddr().trim();
    }

    public static String getUserAgent(HttpServletRequest request) {
        return request.getHeader("User-Agent");
    }

    public static HttpServletRequest getCurrentRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }


    public static String getHeader(String name) {
        return getCurrentRequest().getHeader(name);
    }
}
